package com.maodou.android.ui.page.account

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.abs
import kotlin.math.roundToInt

@Composable
fun BottomWheelPicker(
    title: String,
    items: List<String>,
    initialIndex: Int = 0,
    onConfirm: (index: Int) -> Unit,
    onCancel: (() -> Unit)? = null,
    bottomActionText: String? = null,
    onBottomAction: (() -> Unit)? = null,
    bottomNote: String? = null,
    modifier: Modifier = Modifier,
    itemHeight: Dp = 44.dp,
    visibleCount: Int = 5,
) {
    if (items.isEmpty()) {
        Column(
            modifier = modifier
                .fillMaxWidth()
                .background(Color.White)
                .padding(bottom = 8.dp)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 12.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = "取消",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.clickable { onCancel?.invoke() }
                )
                Spacer(modifier = Modifier.weight(1f))
                Text(
                    text = title,
                    style = MaterialTheme.typography.titleMedium,
                    color = MaterialTheme.colorScheme.onSurface,
                    textAlign = TextAlign.Center
                )
                Spacer(modifier = Modifier.weight(1f))
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Text(
                        text = "完成",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
//            HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(itemHeight * visibleCount),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = "暂无可选项",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
            if (bottomActionText != null) {
                Spacer(modifier = Modifier.height(8.dp))
                Box(
                    modifier = Modifier
                        .padding(horizontal = 16.dp)
                        .fillMaxWidth()
                        .height(40.dp)
                        .background(
                            color = MaterialTheme.colorScheme.primary,
                            shape = RoundedCornerShape(20.dp)
                        )
                        .clickable { onBottomAction?.invoke() },
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = bottomActionText,
                        style = MaterialTheme.typography.labelLarge,
                        color = MaterialTheme.colorScheme.onPrimary
                    )
                }
            }
            if (!bottomNote.isNullOrBlank()) {
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = bottomNote,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(horizontal = 16.dp)
                )
            }
        }
        return
    }

    val listState = rememberLazyListState()
    val scope = rememberCoroutineScope()
    val density = LocalDensity.current

    val centerSlot = remember(visibleCount) { visibleCount / 2 }
    val leadingCount = centerSlot
    val itemHeightPx = with(density) { itemHeight.toPx() }

    LaunchedEffect(initialIndex) {
        val target = initialIndex.coerceIn(0, (items.size - 1).coerceAtLeast(0))
        delay(1)
        listState.scrollToItem(target)
    }

    val centerDataAbsolute by remember {
        derivedStateOf {
            listState.firstVisibleItemIndex + listState.firstVisibleItemScrollOffset / itemHeightPx
        }
    }

    LaunchedEffect(listState.isScrollInProgress) {
        if (!listState.isScrollInProgress) {
            val targetData = centerDataAbsolute.roundToInt().coerceIn(0, items.lastIndex)
            scope.launch { listState.animateScrollToItem(targetData) }
        }
    }

    Column(
        modifier = modifier
            .fillMaxWidth()
            .background(Color.White)
            .padding(bottom = 8.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "取消",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.clickable { onCancel?.invoke() }
            )
            Spacer(modifier = Modifier.weight(1f))
            Text(
                text = title,
                style = MaterialTheme.typography.titleMedium,
                color = MaterialTheme.colorScheme.onSurface,
                textAlign = TextAlign.Center
            )
            Spacer(modifier = Modifier.weight(1f))
            Row(verticalAlignment = Alignment.CenterVertically) {
                val selectedIndex = centerDataAbsolute.roundToInt().coerceIn(0, items.lastIndex)
                Text(
                    text = "完成",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.primary,
                    modifier = Modifier.clickable { onConfirm(selectedIndex) }
                )
            }
        }
//        HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)

        val wheelHeight = itemHeight * visibleCount
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(wheelHeight)
        ) {
//            Box(
//                modifier = Modifier
//                    .fillMaxWidth()
//                    .height(itemHeight)
//                    .align(Alignment.Center)
//                    .padding(horizontal = 12.dp)
//                    .background(
//                        color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.06f),
//                        shape = RoundedCornerShape(12.dp)
//                    )
//                    .border(
//                        width = 1.dp,
//                        color = MaterialTheme.colorScheme.outlineVariant,
//                        shape = RoundedCornerShape(12.dp)
//                    )
//            )

            LazyColumn(
                state = listState,
                modifier = Modifier.fillMaxSize(),
                contentPadding = PaddingValues(0.dp)
            ) {
                items(leadingCount) {
                    Box(modifier = Modifier
                        .fillMaxWidth()
                        .height(itemHeight)) {}
                }
                itemsIndexed(items, key = { i, _ -> i }) { index, label ->
                    val distance = abs(index - centerDataAbsolute)
                    val isCenter = distance < 0.5f
                    val alpha = 1f - (distance * 0.55f).coerceIn(0f, 0.85f)
                    val scale = 1.08f - (distance * 0.20f).coerceIn(0f, 0.28f)
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(itemHeight)
                            .padding(horizontal = 20.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        Text(
                            text = label,
                            color = if (isCenter) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface.copy(alpha = alpha),
                            style = if (isCenter) MaterialTheme.typography.titleMedium else MaterialTheme.typography.titleSmall,
                            fontWeight = if (isCenter) FontWeight.SemiBold else FontWeight.Normal,
                            modifier = Modifier.graphicsLayer {
                                scaleX = scale
                                scaleY = scale
                            },
                            textAlign = TextAlign.Center
                        )
                    }
                }
                items(leadingCount) {
                    Box(modifier = Modifier
                        .fillMaxWidth()
                        .height(itemHeight)) {}
                }
            }

            Box(
                modifier = Modifier
                    .matchParentSize()
                    .background(
                        Brush.verticalGradient(
                            0f to Color.White,
                            0.5f to Color.White.copy(alpha = 0f),
                            1f to Color.White
                        )
                    )
            )
        }

        if (bottomActionText != null) {
            Spacer(modifier = Modifier.height(12.dp))
            Box(
                modifier = Modifier
                    .padding(horizontal = 16.dp)
                    .fillMaxWidth()
                    .height(40.dp)
                    .background(
                        color = MaterialTheme.colorScheme.primary,
                        shape = RoundedCornerShape(20.dp)
                    )
                    .clickable { onBottomAction?.invoke() },
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = bottomActionText,
                    style = MaterialTheme.typography.labelLarge,
                    color = MaterialTheme.colorScheme.onPrimary
                )
            }
        }
        if (!bottomNote.isNullOrBlank()) {
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = bottomNote,
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.padding(horizontal = 16.dp)
            )
        }
    }
}